package com.moyu.article.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moyu.article.domain.comment.Comment;
import com.moyu.article.domain.comment.dto.CommentDTO;
import com.moyu.article.domain.comment.dto.CommentItemQueryDTO;
import com.moyu.article.domain.comment.dto.CommentQueryDTO;
import com.moyu.article.domain.comment.dto.DetailQueryDTO;
import com.moyu.article.domain.comment.vo.CommentListVO;
import com.moyu.article.domain.comment.vo.CommentQueryVO;
import com.moyu.article.domain.comment.vo.CommentVO;
import com.moyu.article.mapper.CommentMapper;
import com.moyu.article.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 赵彦博
 * @Date 2025/3/30 9:28
 */
@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<CommentVO> list(@RequestBody CommentQueryDTO query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return commentMapper.list(query);
    }

    @Override
    public List<String> getCommentByPost(DetailQueryDTO dto) {
        return commentMapper.getCommentByPost(dto);
    }

    @Override
    public CommentListVO getCommentItem(CommentItemQueryDTO dto) {
        return commentMapper.getCommentItem(dto);
    }

    @Override
    public PageInfo<CommentListVO> getCommentList(CommentItemQueryDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<CommentListVO> comments = commentMapper.selectCommentList(dto);

        // 处理点赞状态和子评论
        comments.forEach(comment -> {
            // 设置点赞状态
            if (dto.getCurrentUserId() != null) {
                comment.setIsLiked(commentMapper.checkUserLike(
                        comment.getCommentId(),
                        dto.getCurrentUserId()
                ));
            }

            // 递归处理子评论
            if (dto.getIncludeChildren() && comment.getChildren() != null) {
                processChildrenComments(comment.getChildren(), dto.getCurrentUserId());
            }
        });

        return new PageInfo<>(comments);
    }

    private void processChildrenComments(List<CommentListVO> comments, Long currentUserId) {
        comments.forEach(child -> {
            if (currentUserId != null) {
                child.setIsLiked(commentMapper.checkUserLike(
                        child.getCommentId(),
                        currentUserId
                ));
            }
            if (child.getChildren() != null) {
                processChildrenComments(child.getChildren(), currentUserId);
            }
        });
    }

    @Override
    public int approveComment(String commentId) {
        // 更新评论状态为已通过
        return commentMapper.updateStatus(commentId, 1);
    }

    @Override
    public int rejectComment(String commentId) {
        // 更新评论状态为已拒绝
        return commentMapper.updateStatus(commentId, 2);
    }

    @Override
    public List<CommentQueryVO> getComments(Long postId, Long userId) {
        List<CommentQueryVO> comments = commentMapper.selectCommentsByPostId(postId, userId);

        if (comments == null || comments.size() == 0 || comments.isEmpty()) {
            return comments;
        }
        // 构建评论树
        Map<String, CommentQueryVO> commentMap = new HashMap<>();
        List<CommentQueryVO> rootComments = new ArrayList<>();

        for (CommentQueryVO comment : comments) {
            commentMap.put(comment.getCommentId(), comment);

            if (comment.getParentId() == null) {
                rootComments.add(comment);
            }
        }

        for (CommentQueryVO comment : comments) {
            if (comment.getParentId() != null) {
                CommentQueryVO parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(comment);
                }
            }
        }

        return rootComments;
    }

    @Override
    public Comment createComment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setPostTitle("");
        comment.setNickName(commentDTO.getNickName());
        comment.setPostId(commentDTO.getPostId());
        comment.setParentId(commentDTO.getParentId());
        comment.setContent(commentDTO.getContent());
        comment.setUserId(commentDTO.getUserId());
        comment.setCreateTime(LocalDateTime.now());
        comment.setCreateBy(commentDTO.getUserId());
        commentMapper.insertComment(comment);
        return comment;
    }

    @Override
    public void likeComment(Long commentId, Long userId) {
        if (commentMapper.checkCommentLikeStatus(commentId, userId) > 0) {
            throw new RuntimeException("已经点赞过该评论");
        }
        commentMapper.insertCommentLike(commentId, userId);
    }

    @Override
    public void cancelLikeComment(Long commentId, Long userId) {
        if (commentMapper.checkCommentLikeStatus(commentId, userId) == 0) {
            throw new RuntimeException("还未点赞过该评论");
        }
        commentMapper.deleteCommentLike(commentId, userId);
    }
}
